//
//  LoginViewController.m
//  JiongTu
//
//  Created by 杨璟 on 16/3/15.
//  Copyright © 2016年 YSKJ. All rights reserved.
//


#import "LoginViewController.h"
#import "ControllerManger.h"
#import "FlyHomeViewController.h"
#import "JTProvisionViewController.h"

#import "UIView+Extension.h"
#import "JTUser.h"

#import <SVProgressHUD.h>
#import <AVOSCloud.h>

@interface LoginViewController ()<UITextFieldDelegate>
/**
 *  电话号码输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
/**
 *  验证码输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *codeField;
/**
 *  输入框整体
 */
@property (weak, nonatomic) IBOutlet UIView *inputArea;
/**
 *  获取验证码按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *getSMSCode;

@property (weak, nonatomic) IBOutlet UIButton *provisionBtn;

@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
/**
 *  登录按键
 */
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@end

@implementation LoginViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"登录";
    
    self.phoneField.delegate = self;
    self.codeField.delegate = self;
    
    self.getSMSCode.layer.cornerRadius = 5.0;
    self.getSMSCode.layer.masksToBounds = YES;
    
    //键盘改变通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardDidHideNotification object:nil];
    [self addObserver:self forKeyPath:@"self.sureBtn.selected" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:nil];
    
    [self.provisionBtn addTarget:self action:@selector(provisionClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.sureBtn addTarget:self action:@selector(sureClick:) forControlEvents:UIControlEventTouchUpInside];

}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    
//    const CGFloat offset = CGRectGetHeight([UIScreen mainScreen].bounds);
//    
//    CGPoint backImageCenter = self.loginBG.center;
//    CGPoint accountCenter = self.inputArea.center;
//    CGPoint loginBtnCenter = self.loginBtn.center;
//    
//    CGPoint startBGCenter = CGPointMake(self.loginBG.center.x, self.loginBG.center.y - offset);
//    CGPoint startInputCenter = CGPointMake(self.inputArea.center.x, self.inputArea.center.y + offset);
//    CGPoint startBtnCenter = CGPointMake(self.loginBtn.center.x, self.loginBtn.center.y + offset);
//    
//    self.loginBG.center = startBGCenter;
//    self.inputArea.center = startInputCenter;
//    self.loginBtn.center = startBtnCenter;
//    
//    [UIView animateWithDuration:1 animations: ^{
//        self.loginBG.alpha = 1;
//        self.loginBG.center = backImageCenter;
//    } completion: nil];
//    [UIView animateWithDuration:1 delay:0.75 options:0 animations: ^{
//        self.inputArea.alpha = 1;
//        self.inputArea.center = accountCenter;
//    } completion: ^(BOOL finished) {
//        [UIView animateWithDuration:0.75 delay:0 options:0 animations:^{
//            self.loginBtn.alpha = 1;
//        } completion:nil];
//    }];
//}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeObserver:self forKeyPath:@"self.sureBtn.selected"];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}


#pragma mark - 布局更改
- (void)keyBoardDidShow:(NSNotification *)notification {
    
    NSDictionary *info = notification.userInfo;
    CGRect endFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    double animationDuration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    NSLog(@"min:%f", CGRectGetMinY(self.inputArea.frame));
    NSLog(@"max:%f", CGRectGetMaxY(self.inputArea.frame));
    NSLog(@"kbY:%@", NSStringFromCGRect(endFrame));
    NSLog(@"minus:%f", endFrame.origin.y - self.inputArea.height - 64);
    
    if (endFrame.origin.y - 64 < CGRectGetMaxY(self.inputArea.frame)) {
        [UIView animateWithDuration:animationDuration animations:^{
            self.inputArea.y -= (CGRectGetMaxY(self.inputArea.frame) - endFrame.origin.y + 64);
        }];
    }
}


- (void)keyBoardDidHide:(NSNotification *)notification {
    
    NSDictionary *info = notification.userInfo;
    CGRect endFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    double animationDuration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
}

#pragma mark - 按钮点击
- (IBAction)LogIn:(UIButton *)sender {
    
//    AVUser *user = [AVUser user];// 新建 AVUser 对象实例
//    user.username = @"153358";// 设置用户名
//    user.password =  @"321456987";// 设置密码
//    
//    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//        if (succeeded) {
//            [SVProgressHUD showSuccessWithStatus:@"注册成功"];
//        } else {
//            [SVProgressHUD showErrorWithStatus:@"注册失败"];
//        }
//    }];
    
    if ([self.phoneField.text isEqualToString:@"153358"] && [self.codeField.text isEqualToString:@"321456987"]) {
        [SVProgressHUD showWithStatus:@"正在登录"];
        [AVUser logInWithUsernameInBackground:self.phoneField.text password:self.codeField.text block:^(AVUser *user, NSError *error) {
            if (error) {
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            } else {
                sender.enabled = NO;
                /**
                 *  添加用户的objectId到installation类
                 */
                AVInstallation *installation = [AVInstallation currentInstallation];
                [installation setObject:user.objectId forKey:@"UserInfo"];
                [installation saveInBackground];
                
                NSLog(@"%@", user);
                [[JTUser userWithCurrentUser:user] save];
                
                [self dismissView];
            }
        }];
    } else {
        [SVProgressHUD showWithStatus:@"正在登录"];
        [AVUser signUpOrLoginWithMobilePhoneNumberInBackground:self.phoneField.text smsCode:self.codeField.text block:^(AVUser *user, NSError *error) {
            
            if (error) {
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            } else {
                sender.enabled = NO;
                /**
                 *  添加用户的objectId到installation类
                 */
                AVInstallation *installation = [AVInstallation currentInstallation];
                [installation setObject:user.objectId forKey:@"UserInfo"];
                [installation saveInBackground];
                
                NSLog(@"%@", user);
                [[JTUser userWithCurrentUser:user] save];
                
                [self dismissView];
            }
        }];
    }
    
}

/**
 *  点击获取验证码
 */
- (IBAction)getCode:(id)sender {
    
    [AVOSCloud requestSmsCodeWithPhoneNumber:self.phoneField.text callback:^(BOOL succeeded, NSError *error) {
        NSLog(@"%@", error.userInfo);
        if (succeeded) {
            [SVProgressHUD showSuccessWithStatus:@"已发送，请注意查收"];
            self.getSMSCode.enabled = NO;
            self.getSMSCode.enabled = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.getSMSCode.enabled = YES;
            });
        } else {
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }
    }];
}

- (void)provisionClick:(UIButton *)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    JTProvisionViewController *vc = [sb instantiateViewControllerWithIdentifier:@"provision"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)sureClick:(UIButton *)sender {
    sender.selected = !sender.isSelected;
}

- (void)dismissView {
    [SVProgressHUD showSuccessWithStatus:@"登录成功"];
    
//    const CGFloat offset = CGRectGetHeight([UIScreen mainScreen].bounds);
//    
//    CGPoint startInputCenter = CGPointMake(self.inputArea.center.x, self.inputArea.center.y + offset);
//    CGPoint startBGCenter = CGPointMake(self.loginBG.center.x, self.loginBG.center.y - offset);
//    
//    [UIView animateWithDuration:0.3 animations: ^{
//        self.loginBG.alpha = 0;
//        self.loginBG.center = startBGCenter;
//    } completion:^(BOOL finished) {
//        [self.phoneField resignFirstResponder];
//        [self.codeField resignFirstResponder];
//    }];
//    
//    [UIView animateWithDuration:0.3 delay:0.15 options:0 animations: ^{
//        self.inputArea.alpha = 0;
//        self.inputArea.center = startInputCenter;
//    } completion: ^(BOOL finished) {
//        [UIView animateWithDuration:0.2 delay:0 options:0 animations:^{
//            self.loginBtn.alpha = 0;
//        } completion:^(BOOL finished) {
//            
//            [self dismissViewControllerAnimated:NO completion:nil];
//            
//        }];
//    }];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"self.sureBtn.selected"]) {
        if ([change[@"new"] isEqualToNumber:@(1)]) {
            self.loginBtn.enabled = YES;
        } else {
            self.loginBtn.enabled = NO;
        }
    }
}

@end
